import { defineAppConfig, Link } from 'ice';
import { defineAuthConfig } from '@ice/plugin-auth/types';
import { defineRequestConfig } from '@ice/plugin-request/types';
import { defaultType } from '@/services/user';
import { Message } from '@alifd/next';
import { baseURL } from '@/config/backendUrl';

Message.config({
  maxCount: 3,
  duration: 2000,
});
export default defineAppConfig(() => ({}));
export const authConfig = defineAuthConfig(() => {
  return {
    initialAuth: { admin: false },
    NoAuthFallback: () => {
      return (
        <>
          <Link to="/register">无权限访问</Link>
        </>
      );
    },
  };
});

export const requestConfig = defineRequestConfig({
  // 可选的，全局设置 request 是否返回 response 对象，默认为 false
  withFullResponse: false,
  baseURL: baseURL,
  headers: {},
  // ...RequestConfig 其他参数

  // 拦截器
  interceptors: {
    request: {
      onConfig: (config) => {
        // 发送请求前：可以对 RequestConfig 做一些统一处理
        return config;
      },
      onError: (error) => {
        return Promise.reject(error);
      },
    },
    response: {
      onConfig: (response) => {
        const data = response.data as defaultType<string>;
        if (!data.success) {
          if (data.message == 'jwt expired') {
            Message.warning('令牌已过期请重新登录');
          } else if (data.status == 401) {
            Message.warning('没有权限呢喵~ (★ ω ★)');
          } else {
            Message.warning(data.message);
          }
        }
        return response;
      },
      onError: (error) => {
        if (error.code == 'ERR_NETWORK') {
          Message.warning('网络错误');
        }
        // 请求出错：服务端返回错误状态码
        return Promise.reject(error);
      },
    },
  },
});
